<template>
  <div>
    <BasicModal @register="registerModal" :helpMessage="['查看帮助']" v-bind="$attrs">
      <BasicForm @register="editRegisterFrom">
        <template #addRuleStepSlot>
          <!--步骤进度-->
          <Steps :current="current">
            <Step title="基本设置" />
            <Step :title="endStepName" />
          </Steps>
        </template>
        <template #templateSelectSlot>
          <div style="display: flex">
            <Select
              show-search
              :listHeight="160"
              :show-arrow="false"
              v-model:value="selectTemplate"
              @focus="getSelectList"
            >
              <SelectOption v-for="(item, index) in selectOptions" :key="index" :value="item.name">
                {{ item.name }}
                <Tag
                  :bordered="false"
                  color="blue"
                  v-for="(mItem, index) in item.configuration.deliveryMethodsTemplates"
                  :key="index"
                  >{{ mItem.method }}</Tag
                >
              </SelectOption>
            </Select>
          </div>
        </template>
      </BasicForm>
      <!--底部按钮-->
      <template #footer>
        <Button
          class="mr-2"
          type="primary"
          size="middle"
          @click="stepLastClick"
          v-show="current > 0"
          >后退</Button
        >
        <Button class="mr-2" type="primary" size="middle" @click="stepNextClick">{{
          okText
        }}</Button>
      </template>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { Button, Tag, Steps, Step, Select, SelectOption } from 'ant-design-vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { ref, watch } from 'vue';
  import {
    getTargetsList,
    getTemplatesList,
    createRule,
  } from '/@/api/thingsborad/notification/notification';
  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  const emits = defineEmits(['closeFlag']);
  //模板选择
  let selectTemplate = ref<any>();

  //是否变化
  let isEdit = ref<boolean>(false);

  // 步骤条进度
  let current = ref(0);

  // 编辑是传入的数据
  let editRuleData = ref<any>();

  // 步骤名称
  let endStepName = ref<string>('实体限制触发器设置');

  let stepName = ref<any>({
    ENTITIES_LIMIT: '实体限制触发器设置',
    API_USAGE_LIMIT: 'API使用触发设置',
    NEW_PLATFORM_VERSION: '新平台版本触发设置',
    RATE_LIMITS: 'Exceeded rate limits trigger settings',
  });
  //规则收件人下拉列表数据
  let recipientSelectOptions = ref<any>([]);
  //表单初始化注册
  let editSchemas: FormSchema[] = [
    {
      field: 'addRuleStep',
      component: 'Input',
      slot: 'addRuleStepSlot',
      label: '',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'ruleName',
      component: 'Input',
      label: '规则名称',
      required: true,
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'enableName',
      component: 'Switch',
      label: '启用通知规则',
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'addRuleTrigger',
      component: 'Select',
      label: '触发器',
      required: true,
      defaultValue: 'ENTITIES_LIMIT',
      componentProps: {
        listHeight: 160,
        onclick: async () => {
          //改变步骤名称
          let validateValue = await validate();
          endStepName.value = stepName.value[validateValue.addRuleTrigger];
        },

        options: [
          {
            label: '实体限制',
            value: 'ENTITIES_LIMIT',
          },
          {
            label: 'API使用限制',
            value: 'API_USAGE_LIMIT',
          },
          {
            label: '新的平台版本',
            value: 'NEW_PLATFORM_VERSION',
          },
          {
            label: 'Exceeded rate limits',
            value: 'RATE_LIMITS',
          },
        ],
      },
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'templateSelect',
      component: 'Input',
      slot: 'templateSelectSlot',
      label: '模板',
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'ruleRecipient',
      component: 'Select',
      label: '收件人',
    },
    {
      show: (value) => {
        return current.value === 1 && value.model.addRuleTrigger === 'ENTITIES_LIMIT';
      },
      field: 'filterEntity',
      component: 'Select',
      label: '筛选器实体',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: [
          {
            label: '设备',
            value: 'DEVICE',
          },
          {
            label: '资产',
            value: 'ASSET',
          },
          {
            label: '客户',
            value: 'CUSTOMER',
          },
          {
            label: '用户',
            value: 'USER',
          },
          {
            label: '仪表板',
            value: 'DASHBOARD',
          },
          {
            label: '规则链',
            value: 'RULE_CHAIN',
          },
        ],
      },
    },
    {
      show: (value) => {
        return current.value === 1 && value.model.addRuleTrigger === 'ENTITIES_LIMIT';
      },
      field: 'filterThreshold',
      component: 'Input',
      defaultValue: 0.23,
      label: '筛选器阈值',
    },
    {
      show: (value) => {
        return current.value === 1 && value.model.addRuleTrigger === 'API_USAGE_LIMIT';
      },
      field: 'apiStatistics',
      component: 'Select',
      label: 'Api 统计',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: [
          {
            label: '设备API',
            value: 'TRANSPORT',
          },
          {
            label: '遥测持久化',
            value: 'DB',
          },
          {
            label: '规则引擎执行',
            value: 'RE',
          },
          {
            label: 'JavaScript执行数',
            value: 'JS',
          },
          {
            label: 'TBEL executions',
            value: 'TBEL',
          },
          {
            label: '邮件消息',
            value: 'EMAIL',
          },
          {
            label: '短信消息',
            value: 'SMS',
          },
          {
            label: '告警',
            value: 'ALARM',
          },
        ],
      },
    },
    {
      show: (value) => {
        return current.value === 1 && value.model.addRuleTrigger === 'API_USAGE_LIMIT';
      },
      field: 'notificationConditions',
      component: 'Select',
      label: '通知条件',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: [
          {
            label: '已启用',
            value: 'ENABLED',
          },
          {
            label: '告警',
            value: 'WARNING',
          },
          {
            label: '已禁用',
            value: 'DISABLED',
          },
        ],
      },
    },
    {
      show: (value) => {
        return current.value === 1 && value.model.addRuleTrigger === 'RATE_LIMITS';
      },
      field: 'rateLimits',
      component: 'Select',
      label: '费率限制',
      componentProps: {
        listHeight: 160,
        mode: 'multiple',
        options: [
          {
            label: 'Entity version creation',
            value: 'ENTITY_EXPORT',
          },
          {
            label: 'Entity version load',
            value: 'ENTITY_IMPORT',
          },
          {
            label: 'Notification requests',
            value: 'NOTIFICATION_REQUESTS',
          },
          {
            label: 'Notification requests per rule',
            value: 'NOTIFICATION_REQUESTS_PER_RULE',
          },
          {
            label: 'REST APl requests',
            value: 'REST_REQUESTS_PER_TENANT',
          },
          {
            label: 'REST APl requests per customer',
            value: 'REST_REQUESTS_PER_CUSTOMER',
          },
          {
            label: 'WS updates per session',
            value: 'WS_UPDATES_PER_SESSION',
          },
          {
            label: 'Cassandra queries',
            value: 'CASSANDRA_QUERIES',
          },
          {
            label: 'Transport messages',
            value: 'TRANSPORT_MESSAGES_PER_TENANT',
          },
          {
            label: 'Transport messages per device',
            value: 'TRANSPORT_MESSAGES_PER_DEVICE',
          },
        ],
      },
    },
    {
      show: () => {
        return current.value === 1;
      },
      field: 'describe',
      component: 'InputTextArea',
      label: '描述',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入描述',
      },
    },
  ];
  //创建模板下拉
  let selectOptions = ref<any>([]);
  let okText = ref<string>('下一步');
  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 50,
    page: 0,
    sortProperty: 'name',
    sortOrder: 'ASC',
    notificationType: 'ALARM',
  });
  //设备下拉列表
  let deviceSelectList = ref<any>([]);

  //获取下拉数据
  async function getSelectList() {
    selectOptions.value = [];
    //请求参数
    let params = ref<notificationsParams>({
      pageSize: 10,
      page: 0,
      sortProperty: 'name',
      sortOrder: 'ASC',
      notificationTypes: 'ALARM',
    });
    let switchFlag;
    let triggerFlag = await validate();
    //传参
    switch (triggerFlag.addRuleTrigger) {
      case 'ENTITIES_LIMIT':
        switchFlag = 'ENTITIES_LIMIT';
        break;
      case 'API_USAGE_LIMIT':
        switchFlag = 'API_USAGE_LIMIT';
        break;
      case 'ALARM_COMMENT':
        switchFlag = 'ALARM_COMMENT';
        break;
      case 'NEW_PLATFORM_VERSION':
        switchFlag = 'NEW_PLATFORM_VERSION';
        break;
      case 'RATE_LIMITS':
        switchFlag = 'RATE_LIMITS';
        break;
    }
    params.value.notificationTypes = switchFlag;
    const templatesData = await getTemplatesList(params.value);
    //判空
    if (templatesData.data.length === 0) {
      return;
    }
    selectOptions.value = templatesData.data;
  }
  const [editRegisterFrom, { updateSchema, validate, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: editSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //弹窗初始化
    isEdit.value = false;
    //保持传入的数据
    editRuleData.value = data.info;
    resetFields();
    current.value = 0;
    updateSchema({
      field: 'deviceSelect',
      componentProps: {
        mode: 'multiple',
        listHeight: '160',
        options: deviceSelectList.value,
      },
    });
    setModalProps({
      showCancelBtn: false,
      showOkBtn: false,
      width: 800,
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    //获取收件人下拉列表
    getRecipientSelectList(params.value);
    // 编辑
    if (data !== true) {
      //编辑状态
      isEdit.value = true;
      endStepName.value = stepName.value[data.info.triggerType];
      selectTemplate.value = data.templateName;
      setFieldsValue({
        ruleName: data.name,
        enableName: data.enabled,
        addRuleTrigger: data.info.triggerType,
        ruleRecipient: data.info.recipientsConfig.targets,
        describe: data.description,
      });
      // 实体限制
      if (data.info.triggerType === 'ENTITIES_LIMIT') {
        setFieldsValue({
          filterEntity: data.info.triggerConfig.entityTypes,
          filterThreshold: data.info.triggerConfig.threshold,
        });
      } // API使用限制
      else if (data.info.triggerType === 'API_USAGE_LIMIT') {
        setFieldsValue({
          apiStatistics: data.info.triggerConfig.apiFeatures,
          notificationConditions: data.info.triggerConfig.notifyOn,
        });
      } //
      else if (data.info.triggerType === 'RATE_LIMITS') {
        setFieldsValue({
          rateLimits: data.info.triggerConfig.apis,
        });
      }
      //获取模板数据
      getSelectList();
    }
  });

  //获取收件人数据
  async function getRecipientSelectList(params: notificationsParams) {
    recipientSelectOptions.value = [];
    const targetsData = await getTargetsList(params);
    //判空
    if (targetsData.data.length === 0) {
      return;
    }
    targetsData.data.forEach((item) => {
      recipientSelectOptions.value.push({
        value: item.id.id,
        label: item.name,
      });
    });
    //初始化数据填充
    updateSchema({
      field: 'ruleRecipient',
      componentProps: {
        listHeight: '160',
        mode: 'multiple',
        options: recipientSelectOptions.value,
      },
    });
  }

  //步骤进度下一步点击事件
  async function stepNextClick() {
    // 等于一时保存
    if (current.value === 1) {
      let validateValue = await validate();
      let data: any;
      //获取templateId
      let templateId: any;
      selectOptions.value.forEach((item) => {
        if (item.name === selectTemplate.value) {
          templateId = item.id;
        }
      });

      
      // 实体限制
      if (validateValue.addRuleTrigger === 'ENTITIES_LIMIT') {
        data = {
          name: validateValue.ruleName,
          enabled: validateValue.enableName === undefined ? false : true,
          templateId: templateId,
          triggerType: validateValue.addRuleTrigger,
          recipientsConfig: {
            targets: validateValue.ruleRecipient,
            triggerType: validateValue.addRuleTrigger,
          },
          triggerConfig: {
            entityTypes: validateValue.filterEntity,
            threshold: validateValue.filterThreshold,
            triggerType: validateValue.addRuleTrigger,
          },
          additionalConfig: {
            description: validateValue.describe,
          },
        };
      } else if (validateValue.addRuleTrigger === 'API_USAGE_LIMIT') {
        // API使用限制
        data = {
          name: validateValue.ruleName,
          enabled: validateValue.enableName === undefined ? false : true,
          templateId: templateId,
          triggerType: validateValue.addRuleTrigger,
          recipientsConfig: {
            targets: validateValue.ruleRecipient,
            triggerType: validateValue.addRuleTrigger,
          },
          triggerConfig: {
            apiFeatures: validateValue.apiStatistics,
            notifyOn: validateValue.notificationConditions,
            triggerType: validateValue.addRuleTrigger,
          },
          additionalConfig: {
            description: validateValue.describe,
          },
        };
      } else if (validateValue.addRuleTrigger === 'RATE_LIMITS') {
        data = {
          name: validateValue.ruleName,
          enabled: validateValue.enableName === undefined ? false : true,
          templateId: templateId,
          triggerType: validateValue.addRuleTrigger,
          recipientsConfig: {
            targets: validateValue.ruleRecipient,
            triggerType: validateValue.addRuleTrigger,
          },
          triggerConfig: {
            apis: validateValue.rateLimits,
            triggerType: validateValue.addRuleTrigger,
          },
          additionalConfig: {
            description: validateValue.describe,
          },
        };
      }
      if (isEdit.value) {
        let dataflag = {
          id: editRuleData.value.id,
          createdTime: editRuleData.value.createdTime,
          tenantId: editRuleData.value.tenantId,
          name: data.name,
          enabled: data.enabled,
          templateId: data.templateId,
          triggerType: data.triggerType,
          triggerConfig: data.triggerConfig,
          recipientsConfig: data.recipientsConfig,
          additionalConfig: data.additionalConfig,
          externalId: editRuleData.value.externalId,
          templateName: editRuleData.value.templateName,
          deliveryMethods: editRuleData.value.deliveryMethods,
        };
        data = dataflag;
      }

      await createRule(data);
      resetFields();
      closeModal();
      emits('closeFlag', true);
    }
    //不等于一小于二是加一 必填值
    if (current.value + 1 < 2) {
      await validate();
      current.value += 1;
    }
  }
  //步骤进度后退点击事件
  function stepLastClick() {
    if (current.value - 1 < 0) {
      return;
    }
    current.value -= 1;
  }
  watch(
    () => current.value,
    (nVal) => {
      if (1 === nVal) {
        okText.value = '保存';
      } else {
        okText.value = '下一步';
      }
    },
  );
</script>
